package com.easpeed.elevator.utils;

/**
 * Created by bigyu on 2024/10/18 10:34
 * com.easpeed.elevator.utils
 */

import android.content.Context;
import android.view.ViewGroup;

import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public abstract class WwAdapter<T> extends RecyclerView.Adapter<WwViewHolder> {

    public static final int TYPE_EMPTY = 0;
    public static final int TYPE_NORMAL = 1;

    private List<T> data = new ArrayList<>();

    private boolean isUseEmpty = false;

    private final int mLayoutId;

    public WwAdapter() {
        mLayoutId = getLayoutId();
    }

    public abstract void initRecyclerView(Context mContext, WwAdapter<T> adapter);

    public abstract int getLayoutId();

    public int getEmptyLayoutId() {
        return 0;
    }

    public void setData(List<T> data) {
        this.data = data;
    }

    public List<T> getData() {
        return data;
    }

    public void addData(ArrayList<T> data) {
        this.data.addAll(data);
    }

    public void isUseEmpty(boolean bool) {
        isUseEmpty = bool;
    }

    @Override
    public WwViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_EMPTY) {
            return WwViewHolder.createViewHolder(parent.getContext(), parent, getEmptyLayoutId());
        } else {
            return WwViewHolder.createViewHolder(parent.getContext(), parent, mLayoutId);
        }
    }

    @Override
    public int getItemCount() {
        if (data.isEmpty() && isUseEmpty) {
            return 1;
        }
        return data.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (data.isEmpty() && isUseEmpty) {
            return TYPE_EMPTY;
        }
        return TYPE_NORMAL;
    }

    @Override
    public void onBindViewHolder(WwViewHolder holder, int position) {
        if (getItemViewType(position) == TYPE_EMPTY) {
            // Do nothing for empty view
            emptyView(holder);
        } else {
            convert(holder, data.get(position), position);
        }
    }
   public void emptyView(WwViewHolder holder) {}

    public abstract void convert(WwViewHolder holder, T item, int position);

    public WwAdapter<T> create(Context mContext, List<T> data) {
        setData(data);
        initRecyclerView(mContext, this);
        return this;
    }
}
